package com.etc.service.impl;


import com.etc.dao.*;
import com.etc.model.*;
import com.etc.tool.StringToTimeStamp;
import com.etc.tool.refFormatNowDate;
import com.etc.vo.LeavePaperDateToStringVo;
import com.etc.vo.PublictellVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TeacherServiceImpl {
    @Autowired
    private TeacherMapper teacherInfo;
    @Autowired
    private User_classMapper classInfo;
    @Autowired
    private StudentMapper studentInfo;
    @Autowired
    private Leave_paperMapper leavePaperInfo;
    @Autowired
    private User_attendanceMapper user_attendance;
    @Autowired
    private PublictellMapper publicTellInfo;

    //教师注册
    public void RegisterTeacher(Teacher teacher){
        teacherInfo.insert(teacher);
    }
    //教师注册重复检测
    public Map<String, String> loginRegisterExam(Teacher data){
        Map<String,String> map=new HashMap<String, String>();
        if(studentInfo.findByUsername(data.getUsername()).size() ==0 && teacherInfo.findByUsername(data.getUsername()) == null){
            map.put("Answer","TRUE");
        }
        else{
            map.put("Answer","FALSE");
        }
        return map;
    }
    //教师登录检测
    public Map<String,String> loginExam(Teacher teacher){
        Map<String,String> map=new HashMap<String, String>();
        List<Teacher> list = teacherInfo.findByUsernameAndPassword(teacher.getUsername(),teacher.getPassword());
        if(list.size() !=0){
            map.put("Answer","TRUE");
        }
        else{
            map.put("Answer","FALSE");
        }
        return map;
    }
    //教师登录界面
    public Teacher TeacherLoginUser(String username){
        Teacher teacher = teacherInfo.findByUsername(username);
        return teacher;
    }
    //教师刷新列表
    public List<User_class> TeacherClassNext(String username){
        List<User_class> list = classInfo.findByUsername(username);
        return list;
    }
    //教师创建班级
    public void TeacherCreateClass(String username,String name,String btn_classN){
        User_class user_class = new User_class();
        //用户名
        user_class.setUsername(username);
        //姓名
        user_class.setName(name);
        //老师
        user_class.setUsertype("老师");
        //随机产生node
        user_class.setClassnode(getRandomString(8));
        //班级名
        user_class.setClassname(btn_classN);
        //班级简介
        user_class.setClassdesn("这个人很懒！");
        //老师名字
        user_class.setTeachername(name);
        //班级人数
        user_class.setClassnumber(1);
        classInfo.insert(user_class);
    }
    //教师解散课堂
    public void TeacherBreakClass(String classnode){
        List<User_class> user_class = classInfo.findAllByClassnode(classnode);
        for(User_class data:user_class){
            classInfo.deleteById(data.getId());
        }

        List<User_attendance> user_attendances = user_attendance.findAllByClassnode(classnode);
        for(User_attendance data:user_attendances){
            user_attendance.deleteById(data.getId());
        }
    }
    //教师离开班级
    public void TeacherExitClass(String username ,String classnode){
        User_class user_class = classInfo.findByUsernameAndClassnode(username,classnode);
        classInfo.deleteById(user_class.getId());
        //清空考勤记录
        List<User_attendance> user = user_attendance.findAllByUsernameAndClassnode(username,classnode);
        for(User_attendance data:user){
            user_attendance.deleteById(data.getId());
        }
        //数量减一
        List<User_class> list = classInfo.findAllByClassnode(classnode);
        for(User_class classdata:list){
            //班级人数减1
            classdata.setClassnumber(classdata.getClassnumber()-1);
            classInfo.updateByPrimaryKey(classdata);
        }
    }
    //教师修改班级
    public void TeacherModifyClass(User_class user_class,String username){
        user_class.setUsername(username);
        classInfo.updateByPrimaryKey(user_class);
    }
    //教师加入班级
    public Map<String,String> TeacherEnterClass(String classnode,String username,String name){
        Map<String,String> map = new HashMap<>();
        //1.取出班级考勤中日期的数量
        User_class FirstData = classInfo.findFirstByClassnodeAndUsertype(classnode, "学生");
        User_class user_class = classInfo.findFirstByClassnodeAndUsertype(classnode,"老师");
        //判断是否重复
        User_class user_class1=classInfo.findByUsernameAndClassnode(username,classnode);
        //判断是否存在班级
        if(user_class == null){
            map.put("Answer","NULL");
        }
        else {
            //判断是否重复
            if(user_class1 !=null){
                map.put("Answer","Repeat");
            }
            else {
                User_class data = new User_class();
                data.setUsername(username);
                data.setClassnode(classnode);
                data.setClassdesn(user_class.getClassdesn());
                data.setUsertype("学生");
                data.setClassname(user_class.getClassname());
                data.setName(name);
                data.setTeachername(user_class.getTeachername());
                data.setClassnumber(user_class.getClassnumber());
                classInfo.insert(data);
                //班级数量加一
                List<User_class> list = classInfo.findAllByClassnode(classnode);
                for (User_class classdata : list) {
                    //班级人数加1
                    classdata.setClassnumber(classdata.getClassnumber() + 1);
                    classInfo.updateByPrimaryKey(classdata);
                }
                classInfo.updateByPrimaryKey(user_class);
                //考勤默认设置
                if (FirstData == null) {
                    for (int i = 0; i < 4; i++) {
                        //当前时间
                        String TimeNow = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(Calendar.getInstance().getTime());
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance(TimeNow);
                        user_data.setClassnode(classnode);
                        user_data.setName(name);
                        user_data.setStatus("1");
                        //因为老师没有学号，所以用账号代替
                        user_data.setStudentnumber(username);
                        user_data.setUsername(username);
                        user_attendance.insert(user_data);
                    }
                } else {
                    List<User_attendance> list1 = user_attendance.findAllByUsernameAndClassnodeOrderByIdAsc(FirstData.getUsername(),classnode);
                    for (User_attendance data3 : list1) {
                        User_attendance user_data = new User_attendance();
                        user_data.setAttendance(data3.getAttendance());
                        user_data.setClassnode(data3.getClassnode());
                        user_data.setName(name);
                        user_data.setStatus("1");
                        //因为老师没有学号，所以用账号代替
                        user_data.setStudentnumber(username);
                        user_data.setUsername(username);
                        user_attendance.insert(user_data);
                    }
                    map.put("Answer", "success");
                }
            }

        }
        return map;
    }
    //教师进入考勤页面-班级所有学生信息
    public List<User_class> jumpAttendanceList(String classnode){
        List<User_class> list = classInfo.findAllByUsertypeAndClassnode("学生",classnode);
        return list;
    }
    //教师进入考勤页面-获取身份
    public String jumpAttendanceUsertype(String username,String classnode){
        //获取自己的身份
        String usertype = classInfo.findByUsernameAndClassnode(username,classnode).getUsertype();
        return usertype;
    }
    //教师进入考勤页面-记录班级名
    public User_class jumpAttendanceClassName(String classnode){
        //获取自己的身份
        User_class user_class = classInfo.findFirstByClassnode(classnode);
        return user_class;
    }
    //教师进入考勤页面-获取班级内的名字
    public List<String> jumpAttendanceUser(List<User_class> list){
        List<String> user = new ArrayList<>();
        for(User_class data:list){ user.add(data.getName()); }
        return user;
    }
    //教师进入考勤页面-获取班级内的学号
    public String[] jumpAttendanceStuNum(List<User_class> list){
        String[] stuNumber = new String[100];
        int i = -1;
        for(User_class data:list){
            i++;
            if(studentInfo.findAllByNameAndUsername(data.getName(),data.getUsername()) == null){
                stuNumber[i]=data.getUsername();
            }else {
                stuNumber[i]=studentInfo.findAllByNameAndUsername(data.getName(),data.getUsername()).getStudentnumber();
            }
        }
        return stuNumber;
    }
    //教师进入考勤页面-获取班级内的考勤日期
    public List<String> jumpAttendanceAttendance(List<User_class> list,String HttpClassnode){
        List<String> attendance = new ArrayList<>();
        int i=-1;
        for(User_class data:list){
            i++;
            List<User_attendance> attendance_data = user_attendance.findAllByUsernameAndClassnodeOrderByIdAsc(data.getUsername(),HttpClassnode);
            //得到考勤的所有日期
            if(i == 0){
                for(User_attendance data1: attendance_data){
                    attendance.add(data1.getAttendance());
                }
            }
        }
        return attendance;
    }
    //教师进入考勤页面-获取班级内的考勤状态
    public String[][] jumpAttendanceAll_data(List<User_class> list,String HttpClassnode){
        int i=-1,j=-1;
        int member_number = list.size();
        String[][] all_data = new String[member_number][100];
        for(User_class data:list){
            i++;
            List<User_attendance> attendance_data = user_attendance.findAllByUsernameAndClassnodeOrderByIdAsc(
                    data.getUsername(),HttpClassnode);
            //得到每个用户不同日期的不同状态
            for(User_attendance data1: attendance_data){
                j++;
                all_data[i][j]=data1.getStatus();
            }
            j=-1;
        }
        return all_data;
    }
    //教师进入考勤页面-整合Excel数据
    public List<Map<String,String>> jumpAttendanceExportExcelList(List<String> user,List<String> attendance,String[][] all_data){
        List<Map<String,String>> exportExcelList = new ArrayList<>();
        //第一行的Username和考勤日期名
        Map<String,String> mapOne= new HashMap<>();
        mapOne.put("1","Username");
        int x =1;
        for(String attendance_data : attendance) {
            x++;
            mapOne.put(x + "", attendance_data);
        }
        exportExcelList.add(mapOne);
        //后面几行
        int p =-1,y=1;
        for(String user_data:user){
            Map<String,String> mapNext= new HashMap<>();
            mapNext.put("1",user_data);
            p++;
            for(int q = 0 ; q < attendance.size(); q++){
                y++;
                if(all_data[p][q].equals("1")){
                    mapNext.put(y+"","出勤");
                }else if(all_data[p][q].equals("0")){
                    mapNext.put(y+"","旷课");
                }else if(all_data[p][q].equals("2")){
                    mapNext.put(y+"","请假");
                }else if(all_data[p][q].equals("-1")){
                    mapNext.put(y+"","迟到");
                }
            }
            y=1;
            exportExcelList.add(mapNext);
        }
        return exportExcelList;
    }
    //教师新建考勤日期
    public void createAttendance(String HttpClassnode){
        //1.获取该班级所有的成员信息
        List<User_class> user_class = classInfo.findAllByUsertypeAndClassnode("学生",HttpClassnode);
        //2.获取当前年月日
        String TimeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
        //3.将当前日期作为新的考勤进行赋值
        for(User_class data:user_class){
            User_attendance data2 = new User_attendance();
            data2.setUsername(data.getUsername());
            data2.setStatus("1");
            data2.setName(data.getName());
            data2.setClassnode(data.getClassnode());
            data2.setAttendance(TimeNow);
            //判别是否是老师，如果是，那么用账号代替学号
            Student student = studentInfo.findFirstByUsername(data.getUsername());
            if(student != null){
                data2.setStudentnumber(student.getStudentnumber());
            }else{
                data2.setStudentnumber(data.getUsername());
            }
            user_attendance.insert(data2);
        }
    }
    //教师修改考勤日期
    public void ModifyAttendance(String attendance_Old ,String attendance_New ,String HttpClassnode){
        //1.获取旧的考勤日期名字，得到所有数据
        List<User_attendance> list_user_attendance = user_attendance.findAllByAttendanceAndClassnode(attendance_Old,HttpClassnode);
        //2.新旧进行比较
        if(!attendance_Old.equals(attendance_New)){
            //3.新的代替旧的
            for(User_attendance data : list_user_attendance){
                data.setAttendance(attendance_New);
                user_attendance.updateByPrimaryKey(data);
            }
        }
    }
    //教师修改考勤状态
    public void ModifyAttendanceStatus(String type ,String number ,String user,String HttpClassnode){
        List<User_attendance> list = user_attendance.findAllByNameAndClassnodeOrderByIdAsc(user,HttpClassnode);
        int i=-1;
        for(User_attendance data:list){
            i++;
            if(i == Integer.valueOf(number)){
                //出勤
                if(type.equals("check")){
                    data.setStatus("1");
                }
                //旷课
                else if(type.equals("close")){
                    data.setStatus("0");
                }
                //迟到
                else if(type.equals("warning")){
                    data.setStatus("-1");
                }
                //请假
                else {
                    data.setStatus("2");
                }
                user_attendance.updateByPrimaryKey(data);
            }
        }
    }
    //教师删除考勤信息
    public void DeleteAttendance(String attendance ,String HttpClassnode){
        //1.获取该班级该考勤日期的所有数据
        List<User_attendance> list = user_attendance.findAllByAttendanceAndClassnode(attendance,HttpClassnode);
        //2.进行删除
        for(User_attendance data:list){
            user_attendance.deleteById(data.getId());
        }
    }
    //教师成员页面
    public List<User_class> jumpmember(String HttpClassnode){
        List<User_class> allClass= classInfo.findAllByUsertypeAndClassnode("学生",HttpClassnode);
        return  allClass;
    }
    //教师成员页面-删除成员
    public void DeleteStudentInfo(int id){
        User_class user_class1 =classInfo.findById(id);
        List<User_attendance> user_attendances=user_attendance.findAllByUsernameAndClassnode(user_class1.getUsername(),user_class1.getClassnode());
        user_attendance.deleteAll(user_attendances);
        //班级数量jian一
        List<User_class> list = classInfo.findAllByClassnode(user_class1.getClassnode());
        for (User_class classdata : list) {
            //班级人数加1
            classdata.setClassnumber(classdata.getClassnumber() - 1);
            classInfo.updateByPrimaryKey(classdata);
        }
        classInfo.deleteById(id);
    }
    //教师通知页面
    public List<Publictell> jumppublictell(String HttpClassnode){
        List<Publictell> publictells=publicTellInfo.findByClassnode(HttpClassnode);
        return publictells;
    }
    //教师通知界面-插入公告
    public PublictellVo submitPublictell(Publictell publictell,String HttpUsername,String HttpClassnode){
        PublictellVo publictellVos =new PublictellVo();
        String creat_time;
        Teacher teacher = new Teacher();
        teacher= teacherInfo.findFirstByUsername(HttpUsername);
        creat_time =refFormatNowDate.getNowDate();
        publictell.setCreatTime(creat_time);
        publictell.setTeacherName(teacher.getName());
        publictell.setClassnode(HttpClassnode);
        publicTellInfo.insert(publictell);
        List<Publictell> publictells=publicTellInfo.findByClassnode(HttpClassnode);

        publictellVos.setIsPublish("有");
        publictellVos.setPublictell(publictells);
        return publictellVos;
    }
    //教师通知页面-删除通知
    public void DeleteStudentPublictell(int id){
        publicTellInfo.deleteById(id);
    }
    //教师特殊情况页面
    public List<LeavePaperDateToStringVo> jumpSpecialcase(String HttpUsername,String HttpClassnode){
        Teacher teacher= teacherInfo.findFirstByUsername(HttpUsername);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        List<Leave_paper> list  =leavePaperInfo.findByTeacherNameAndStatusAndClassnode(teacher.getName(),"未审核",HttpClassnode);
        List<LeavePaperDateToStringVo> leavePaperDateToStringVos =new ArrayList<>();
        for(Leave_paper leave_paper: list){
            LeavePaperDateToStringVo leavePaperDateToStringVo = new LeavePaperDateToStringVo();
            leavePaperDateToStringVo.setCreatTime(sf.format(leave_paper.getCreatTime()));
            leavePaperDateToStringVo.setEndTime(sf.format(leave_paper.getEndTime()));
            leavePaperDateToStringVo.setStartTime(sf.format(leave_paper.getStartTime()));
            leavePaperDateToStringVo.setClassnode(leave_paper.getClassnode());
            leavePaperDateToStringVo.setId(leave_paper.getId());
            leavePaperDateToStringVo.setLeaveByone(leave_paper.getLeaveByone());
            leavePaperDateToStringVo.setLeaveInfo(leave_paper.getLeaveInfo());
            leavePaperDateToStringVo.setStatus(leave_paper.getStatus());
            leavePaperDateToStringVo.setStudentNumber(leave_paper.getStudentNumber());
            leavePaperDateToStringVo.setTeacherName(leave_paper.getTeacherName());
            leavePaperDateToStringVos.add(leavePaperDateToStringVo);
        }
        return leavePaperDateToStringVos;
    }
    //教师特殊情况页面-同意假条
    public void agreeStudentLeavePaper(int id){
        Leave_paper leave_paper = leavePaperInfo.findFirstById(id);
        leave_paper.setStatus("已审核");
        leavePaperInfo.updateByPrimaryKey(leave_paper);
    }
    //随机产生码
    private static String getRandomString(int length) {
        String base = "ABCDEFGHIJKLMNOPQESDUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
